<template>
  <el-dialog
    v-model="dialogVisible"
    title="系统管理"
    width="700px"
    :before-close="handleClose"
  >
    <div class="system-management">
      <!-- 缓存管理 -->
      <el-card class="management-card">
        <template #header>
          <div class="card-header">
            <el-icon><Refresh /></el-icon>
            <span>缓存管理</span>
          </div>
        </template>
        <div class="card-content">
          <p class="description">
            刷新敏感词缓存，确保最新的敏感词配置立即生效。建议在批量修改敏感词后执行此操作。
          </p>
          <el-button
            type="primary"
            :loading="refreshCacheLoading"
            @click="handleRefreshCache"
          >
            <el-icon><Refresh /></el-icon>
            刷新缓存
          </el-button>
        </div>
      </el-card>

      <!-- 数据清理 -->
      <el-card class="management-card">
        <template #header>
          <div class="card-header">
            <el-icon><Delete /></el-icon>
            <span>数据清理</span>
          </div>
        </template>
        <div class="card-content">
          <p class="description">
            清理过期的统计数据，释放存储空间。可以设置保留天数，默认保留30天的数据。
          </p>
          <div class="clean-form">
            <el-form :inline="true">
              <el-form-item label="保留天数">
                <el-input-number
                  v-model="cleanDays"
                  :min="1"
                  :max="365"
                  controls-position="right"
                  style="width: 120px"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  type="warning"
                  :loading="cleanStatsLoading"
                  @click="handleCleanExpiredStats"
                >
                  <el-icon><Delete /></el-icon>
                  清理数据
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-card>

      <!-- 过滤测试 -->
      <el-card class="management-card">
        <template #header>
          <div class="card-header">
            <el-icon><Search /></el-icon>
            <span>过滤测试</span>
          </div>
        </template>
        <div class="card-content">
          <p class="description">
            测试敏感词过滤功能，输入文本内容查看过滤效果。
          </p>
          <div class="test-form">
            <el-form>
              <el-form-item label="测试内容">
                <el-input
                  v-model="testContent"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入要测试的文本内容"
                  maxlength="1000"
                  show-word-limit
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  type="success"
                  :loading="testFilterLoading"
                  :disabled="!testContent.trim()"
                  @click="handleTestFilter"
                >
                  <el-icon><Search /></el-icon>
                  测试过滤
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 测试结果 -->
          <div v-if="testResult" class="test-result">
            <el-divider>测试结果</el-divider>

            <div class="result-item">
              <label>原始内容：</label>
              <div class="content-box original">
                {{ testResult.originalContent }}
              </div>
            </div>

            <div class="result-item">
              <label>过滤后内容：</label>
              <div class="content-box filtered">
                {{ testResult.filteredContent }}
              </div>
            </div>

            <div class="result-item">
              <label>检测结果：</label>
              <div class="detection-info">
                <el-tag
                  :type="testResult.hasSensitiveWords ? 'danger' : 'success'"
                >
                  {{ testResult.hasSensitiveWords ? "包含敏感词" : "无敏感词" }}
                </el-tag>
                <el-tag v-if="testResult.isBlocked" type="danger" class="ml-2">
                  内容被拦截
                </el-tag>
              </div>
            </div>

            <div
              v-if="testResult.sensitiveWords.length > 0"
              class="result-item"
            >
              <label>敏感词详情：</label>
              <div class="sensitive-words">
                <div
                  v-for="(word, index) in testResult.sensitiveWords"
                  :key="index"
                  class="sensitive-word-item"
                >
                  <el-tag
                    type="danger"
                    size="small"
                    :style="{
                      backgroundColor: getSeverityColor(word.severity),
                      color: '#ffffff',
                      border: 'none'
                    }"
                  >
                    {{ word.word }}
                  </el-tag>
                  <span class="word-info">
                    {{ getTypeDescription(word.type) }} -
                    {{ getSeverityDescription(word.severity) }} -
                    {{ getFilterModeDescription(word.filterMode) }}
                    <span v-if="word.replacement">
                      (替换为: {{ word.replacement }})
                    </span>
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Refresh, Delete, Search } from "@element-plus/icons-vue";
import {
  refreshCacheApi,
  cleanExpiredStatsApi,
  testFilterApi,
  type TestFilterResult,
  SensitiveWordManagementUtils,
  type SensitiveWordType,
  type SeverityLevel,
  type FilterMode
} from "@/api/sensitive-word-management";

// Props
interface Props {
  visible: boolean;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  "update:visible": [value: boolean];
}>();

// 响应式数据
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

const refreshCacheLoading = ref(false);
const cleanStatsLoading = ref(false);
const testFilterLoading = ref(false);
const cleanDays = ref(30);
const testContent = ref("");
const testResult = ref<TestFilterResult | null>(null);

// 刷新缓存
const handleRefreshCache = async () => {
  try {
    refreshCacheLoading.value = true;

    const response = await refreshCacheApi();

    if (response.code === 200) {
      ElMessage.success("缓存刷新成功");
    } else {
      ElMessage.error(response.message || "缓存刷新失败");
    }
  } catch (error) {
    console.error("刷新缓存失败:", error);
    ElMessage.error("刷新缓存失败");
  } finally {
    refreshCacheLoading.value = false;
  }
};

// 清理过期统计
const handleCleanExpiredStats = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要清理 ${cleanDays.value} 天前的统计数据吗？此操作不可恢复。`,
      "确认清理",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    cleanStatsLoading.value = true;

    const response = await cleanExpiredStatsApi(cleanDays.value);

    if (response.code === 200) {
      ElMessage.success(`清理完成，共清理了 ${response.data} 条过期数据`);
    } else {
      ElMessage.error(response.message || "清理失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("清理过期统计失败:", error);
      ElMessage.error("清理失败");
    }
  } finally {
    cleanStatsLoading.value = false;
  }
};

// 测试过滤
const handleTestFilter = async () => {
  if (!testContent.value.trim()) {
    ElMessage.warning("请输入测试内容");
    return;
  }

  try {
    testFilterLoading.value = true;

    const response = await testFilterApi({ content: testContent.value });

    if (response.code === 200) {
      testResult.value = response.data;
    } else {
      ElMessage.error(response.message || "测试失败");
    }
  } catch (error) {
    console.error("测试过滤失败:", error);
    ElMessage.error("测试失败");
  } finally {
    testFilterLoading.value = false;
  }
};

// 工具函数
const getTypeDescription = (type: SensitiveWordType) => {
  return SensitiveWordManagementUtils.getTypeDescription(type);
};

const getSeverityDescription = (severity: SeverityLevel) => {
  return SensitiveWordManagementUtils.getSeverityDescription(severity);
};

const getFilterModeDescription = (mode: FilterMode) => {
  return SensitiveWordManagementUtils.getFilterModeDescription(mode);
};

const getSeverityColor = (severity: SeverityLevel) => {
  return SensitiveWordManagementUtils.getSeverityColor(severity);
};

// 关闭对话框
const handleClose = () => {
  // 重置数据
  testContent.value = "";
  testResult.value = null;
  cleanDays.value = 30;

  dialogVisible.value = false;
};
</script>

<style scoped>
.system-management {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.management-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  gap: 8px;
  align-items: center;
  font-weight: 600;
}

.card-content {
  padding: 16px 0;
}

.description {
  margin: 0 0 16px;
  font-size: 14px;
  line-height: 1.5;
  color: #606266;
}

.clean-form,
.test-form {
  margin-top: 16px;
}

.test-result {
  margin-top: 20px;
}

.result-item {
  margin-bottom: 16px;
}

.result-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #303133;
}

.content-box {
  padding: 12px;
  font-family: monospace;
  word-break: break-all;
  white-space: pre-wrap;
  border-radius: 4px;
}

.content-box.original {
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
}

.content-box.filtered {
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
}

.detection-info {
  display: flex;
  gap: 8px;
  align-items: center;
}

.sensitive-words {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.sensitive-word-item {
  display: flex;
  gap: 8px;
  align-items: center;
}

.word-info {
  font-size: 12px;
  color: #606266;
}

.ml-2 {
  margin-left: 8px;
}

.dialog-footer {
  text-align: right;
}
</style>
